package com.auxgroup.smarthome.enterprise.service;

import com.alibaba.fastjson.JSONObject;
import com.auxgroup.smarthome.enterpriseapi.EnterpriseApi;
import com.auxgroup.smarthome.enterpriseapi.requestbody.auxrequest.AuxDeviceAggDataBody;
import com.auxgroup.smarthome.enterpriseapi.responsebody.auxresult.*;
import com.auxgroup.smarthome.utils.NewDateUtils;
import com.auxgroup.smarthome.web.ApiResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Iterator;
import java.util.List;

/**
 * @Author: laiqiuhua.
 * @Date: 2017/8/18 13:22.
 */
@Service
public class AuxAnalysisService {
    /**
     * 奥克斯统计接口访问秘钥
     */
    private  String token = "d0e6307b89284671abe6450a1f31d55d";

    @Autowired
    private ProductService productService;

    /**
     * 设备概览
     * @param deviceModel 设备型号, 选填
     * @return
     */
    public ApiResponse<AuxDeviceSummaryResult> auxDeviceSummary(String deviceModel){
        AuxDeviceSummaryResult  resultResponse = EnterpriseApi.Aux.auxDeviceSummary(token, deviceModel);
        if(StringUtils.isNotEmpty(resultResponse.getError_code())) {
            return ApiResponse.prompt(resultResponse.getError_code(), resultResponse.getError_message());
        }
        return ApiResponse.ok(resultResponse);
    }

    /**
     * 设备趋势
     * @param start  格式：yyyy-MM-dd
     * @param end 格式：yyyy-MM-dd
     * @param deviceModel  设备型号选填
     * @return
     */
    public ApiResponse<AuxDeviceTrendResult> auxDeviceTrend(String start, String end, String deviceModel){
        AuxDeviceTrendResult  resultResponse = EnterpriseApi.Aux.auxDeviceTrend(token, start, end, deviceModel);
        if(StringUtils.isNotEmpty(resultResponse.getError_code())) {
            return ApiResponse.prompt(resultResponse.getError_code(), resultResponse.getError_message());
        }
        return ApiResponse.ok(resultResponse);
    }

    /**
     * 设备功能使用情况
     * @param deviceModel 设备型号，选填
     * @return
     */
    public ApiResponse<AuxDatapointDetailResult> auxDatapointDetail(String deviceModel){
        AuxDatapointDetailResult  resultResponse = EnterpriseApi.Aux.auxDatapointDetail(token, deviceModel);
        if(StringUtils.isNotEmpty(resultResponse.getError_code())) {
            return ApiResponse.prompt(resultResponse.getError_code(), resultResponse.getError_message());
        }
        return ApiResponse.ok(resultResponse);
    }

    /**
     * 设备分布情况
     * @param type 设备类型：device/fault  必填
     * @param deviceModel 设备型号，选填
     * @return
     */
    public ApiResponse<JSONObject> auxDeviceDistribution(String type, String deviceModel){
        JSONObject  resultResponse = EnterpriseApi.Aux.auxDeviceDistribution(token, type, deviceModel);
        if(StringUtils.isNotEmpty(resultResponse.getString("error_code"))) {
            return ApiResponse.prompt(resultResponse.getString("error_code"), resultResponse.getString("error_message"));
        }
        return ApiResponse.ok(resultResponse);
    }

    /**
     * 故障分析情况
     * @param deviceModel 设备型号，选填
     * @return
     */
    public ApiResponse<AuxDeviceErrorDetailResult> auxDeviceErrorDetail(String deviceModel){
        AuxDeviceErrorDetailResult  resultResponse = EnterpriseApi.Aux.auxDeviceErrorDetail(token, deviceModel);
        if(StringUtils.isNotEmpty(resultResponse.getError_code())) {
            return ApiResponse.prompt(resultResponse.getError_code(), resultResponse.getError_message());
        }
        return ApiResponse.ok(resultResponse);
    }

    /**
     * 用户概览
     * @param deviceModel 设备型号，选填
     * @return
     */
    public ApiResponse<AuxUserSummaryResult> auxUserSummary(String deviceModel){
        AuxUserSummaryResult  resultResponse = EnterpriseApi.Aux.auxUserSummary(token, deviceModel);
        if(StringUtils.isNotEmpty(resultResponse.getError_code())) {
            return ApiResponse.prompt(resultResponse.getError_code(), resultResponse.getError_message());
        }
        return ApiResponse.ok(resultResponse);
    }

    /**
     * 用户趋势
     * @param start 开始时间，格式：yyyy-MM-dd
     * @param end 结束时间，格式：yyyy-MM-dd
     * @param deviceModel 设备型号，选填
     * @return
     */
    public ApiResponse<AuxUserTrendResult> auxUserTrend(String start, String end, String deviceModel){
        AuxUserTrendResult  resultResponse = EnterpriseApi.Aux.auxUserTrend(token, start, end, deviceModel);
        if(StringUtils.isNotEmpty(resultResponse.getError_code())) {
            return ApiResponse.prompt(resultResponse.getError_code(), resultResponse.getError_message());
        }
        return ApiResponse.ok(resultResponse);
    }

    /**
     * 用户数量分布情况
     * @param deviceModel
     * @return
     */
    public ApiResponse<JSONObject> AuxUserDistribution(String deviceModel){
        JSONObject result = EnterpriseApi.Aux.auxUserDistribution(token, deviceModel);
        return ApiResponse.ok(result);
    }

    /**
     * 用户增长历史
     * @param startDate
     * @param endDate
     * @return
     */
    public ApiResponse<List<AuxUserIncrHistory>> auxUserIncreaseHistory(String startDate, String endDate){
        List<AuxUserIncrHistory> result = EnterpriseApi.Aux.auxUserIncreaseHistory(token, startDate, endDate);
        return ApiResponse.ok(result);
    }

    /**
     * 用户地理位置分布
     * @return
     */
    public ApiResponse<JSONObject> auxUserLocationDistribution(){
        JSONObject result = EnterpriseApi.Aux.auxUserLocationDistribution(token);
        return ApiResponse.ok(result);
    }

    /**
     * 用户总数
     * @return
     */
    public ApiResponse<AuxUserTotal> auxUserTotal(){
        AuxUserTotal result = EnterpriseApi.Aux.auxUserTotal(token);
        return ApiResponse.ok(result);
    }


    /**
     * wifi聚合数据
     * @param pk
     * @param did
     * @param body
     * @return
     */
    public ApiResponse<AuxAggDataResult> wifiDeviceAggData(String pk, String did, AuxDeviceAggDataBody body) {
        AuxAggDataResult  resultResponse = EnterpriseApi.Aux.wifiDeviceAggData(productService.getToken(pk), pk, did, body);
        if(StringUtils.isNotEmpty(resultResponse.getError_code())) {
            return ApiResponse.prompt(resultResponse.getError_code(), resultResponse.getError_msg());
        }
        return ApiResponse.ok(resultResponse);
    }

    /**
     * 获取设备用电数据详细信息
     * @param pk
     * @param did
     * @param timeStr
     * @param unit
     * @return
     */
    public AuxAggDataResult getElectricityAggDataInfo(String pk,String did,String timeStr,String unit){
        AuxDeviceAggDataBody body = null;
        //别吐槽，我们也很无奈，这里调用平台的接口，后面实现的格式与先前约定的格式 不一样啦，而且前端已经做啦，为避免前端修改，后台做兼容
        if ("HOURS".equals(unit)){ // 此时的timeStr的格式为 yyyyMMdd  获取每小时维度的用电总量
            body = new AuxDeviceAggDataBody(timeStr+"00", NewDateUtils.getNextDayStr(timeStr)+"00","electricity","sum",unit);
        }
        if ("DAYS".equals(unit)){// 此时的timeStr的格式为 yyyyMM  获取每日维度的用电总量
            body = new AuxDeviceAggDataBody(timeStr+"01"+"00", NewDateUtils.getNextMonthDay(timeStr)+"00","electricity","sum",unit);
        }
        if ("MONTHS".equals(unit)){// 此时的timeStr的格式为 yyyy 获取每月维度的用电总量
            body = new AuxDeviceAggDataBody(timeStr+"010100", (Integer.parseInt(timeStr) + 1)+"010100","electricity","sum",unit);
        }
        ApiResponse<AuxAggDataResult> apiResponse = wifiDeviceAggData(pk, did, body);
        if (!apiResponse.isNotErrorCode())
            throw new IllegalArgumentException("errcode:"+apiResponse.getCode() + ", errMsg:"+ apiResponse.getMessage());
        AuxAggDataResult data = apiResponse.getData();
        if (data == null)
            throw new IllegalArgumentException("电量聚合数据为空");
        return data;
    }


    private static final String ATRR_ELCTRITY = "electricity";

    private static final String AGGREGATOR = "sum";

    private static final String HOURS = "HOURS";

    private static final String DAYS = "DAYS";

    /**
     * 用于波峰，波谷 电量求和计算的共用方法
     * @param pk
     * @param did
     * @param body
     * @return
     */
    private ApiResponse<Float> getPVAggData(String pk, String did,AuxDeviceAggDataBody body){
        ApiResponse<AuxAggDataResult> resultResponse = wifiDeviceAggData(pk, did, body);
        if(!resultResponse.isNotErrorCode()) {
            return ApiResponse.prompt(resultResponse.getCode(), resultResponse.getMessage());
        }
        AuxAggDataResult auxAggDataResult = resultResponse.getData();
        float total = 0;
        if (auxAggDataResult==null){
            return ApiResponse.ok(total);
        }
        float totalElectricity = auxAggDataResult.getTotalElectricity();
        return ApiResponse.ok(totalElectricity);
    }

    /**
     * 求每天波峰或者波谷的用电总量
     * @param pk
     * @param did
     * @param start  波峰(谷)起始时间 时间格式："2017091010" 即2017-9-10 10：00 am
     * @param end    波峰(谷)结束时间
     * @return
     */
    public ApiResponse<Float> getPeakValleyTotalElectric(String pk, String did, String start, String end){
        AuxDeviceAggDataBody body = new AuxDeviceAggDataBody(start,end,ATRR_ELCTRITY,AGGREGATOR,HOURS);
        return getPVAggData(pk,did,body);
    }


    /**
     * 求每天的用电总量
     * @param pk
     * @param did
     * @param date 时间格式："20170910" 即2017-9-10
     * @return
     */
    public ApiResponse<Float> getTotalElectric(String pk, String did,String date){
        AuxDeviceAggDataBody body = new AuxDeviceAggDataBody(date+"00",NewDateUtils.getNextDayStr(date)+"00",ATRR_ELCTRITY,AGGREGATOR,HOURS);
        return getPVAggData(pk,did,body);
    }

    /**
     * 获取产品透传数据点
     * @param pk
     * @return
     */
    public ApiResponse<List<ExtDatapointResult>> getProductExtDatapoint(String pk) {
        List<ExtDatapointResult>  resultResponse = EnterpriseApi.Aux.getExtDatapoint(productService.getToken(pk), pk);
        return ApiResponse.ok(resultResponse);
    }

    /**
     * 是否存在数据点
     * @param pk
     * @param datapoint
     * @return
     */
    public boolean isHasDatapoint(String pk,String datapoint){
        List<ExtDatapointResult>  resultResponse = EnterpriseApi.Aux.getExtDatapoint(productService.getToken(pk), pk);
        for(Iterator<ExtDatapointResult> iterator = resultResponse.iterator();iterator.hasNext();){
            ExtDatapointResult datapointResult = iterator.next();
            if (datapointResult.getName().equals(datapoint)){
                return true;
            }
        }
        return false;
    }

    /**
     * 获取设备最新状态，包含可写数据点值
     * 普通控制：0（CMD：0680）
     * 普通控制采集：1（CMD：0700）
     * 状态采集：2（CMD：0700）
     * 睡眠曲线控制：3（CMD：0680）
     * 睡眠曲线采集：4（CMD：0700）
     * 高级控制：5 （峰谷电等）（CMD：0680）
     * @param pk
     * @param did
     * @param cmd
     * @param src
     * @return
     */
    public ApiResponse<JSONObject> getLatestDataByCmdAndSrc(String pk, String did, String cmd, Integer src) {
        if (StringUtils.isBlank(cmd)) {
            return ApiResponse.prompt(-1, "cmd必填");
        }
        if (null == src) {
            return ApiResponse.prompt(-1, "src必填");
        }
        JSONObject resultResponse = EnterpriseApi.Aux.getLatestDataByCmdAndSrc(productService.getToken(pk), pk, did, cmd, src.toString());
        if (StringUtils.isNotEmpty(resultResponse.getString("error_code"))) {
            ApiResponse.prompt(resultResponse.getString("error_code"), resultResponse.getString("error_message"));
        }
        return ApiResponse.ok(resultResponse);
    }

}
